
from abc import ABCMeta
import sys, logging
import pandas as pd

logging.basicConfig(
    format = "%(asctime)s %(levelname)s:%(name)s: %(message)s",
    level = logging.INFO,
    datefmt = "%H:%M:%S",
    stream = sys.stderr
)
logger = logging.getLogger(__name__)


class ReadFile(metaclass=ABCMeta):
    
    def __init__(self, main_path, source_name):
        """
        main_path: Path, eg: Path('Y:\广告\【共用】媒介报告\阿语RoS\账户组\【KOH】账户组报告')
        source_name: str, eg: data_daily
        """
        self._main_path = main_path
        self._source_name = source_name
        self._df_source = None

    
    @property
    def df_source(self):
        return self._df_source

    # 读取csv文件，返回dataframe
    def read_csv(self, filepath):
        df = pd.DataFrame()
        try:
            df = pd.read_csv(filepath)
            logger.info(f'从[{filepath}]读取数据成功！')
        except Exception as e:
            logger.exception(f'从[{filepath}]读取数据失败，错误原因：{e}')
        return df

    # 读取excel文件，返回dataframe
    def read_excel(self, filepath, sheetName=0, header: int=0):
        df = pd.DataFrame()
        try:
            df = pd.read_excel(filepath, sheet_name = sheetName, header = header)
            logger.info(f'从[{filepath}]读取数据成功！')
        except Exception as e:
            logger.exception(f'从[{filepath}]读取数据失败，错误原因：{e}')
        return df

    # 读取数据源,若存在csv或者xlsx格式文件则读取并返回True,否则返回False
    def read_source(self):
        source_filepath = self._main_path.joinpath('数据源', self._source_name + '.xlsx')
        if source_filepath.exists():
            self._df_source = self.read_excel(source_filepath, header=1)
        else:
            source_filepath = self._main_path.joinpath('数据源', self._source_name + '.csv')
            if source_filepath.exists():
                self._df_source = self.read_csv(source_filepath)
            else:
                return False
        return True
